package ppp.hhh.the.aop;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Slf4j
public class AopLog {
    ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Pointcut("execution(* ppp.hhh.the.controller..*.*(..))")
    public void aopWebLog(){
    }
    @Before("aopWebLog()")
    public void doBefore(JoinPoint joinPoint) throws Exception{
        startTime.set(System.currentTimeMillis());
        //接收到请求 记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        log.info("URL : {}",request.getRequestURL());
        log.info("HTTP_METHOD : {}",request.getMethod());
        log.info("IP : {}",request.getRemoteAddr());
        log.info("CLASS_METHOD : {}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        log.info("ARGS : {}",joinPoint.getArgs());
    }
    @AfterReturning(pointcut = "aopWebLog()",returning = "retObject")
    public void doAfterReturning(Object retObject)throws Exception{
        log.info("RESPONSE : {}",retObject);
        log.info("SPEND TIME : {}ms",System.currentTimeMillis()-startTime.get());
    }
    @AfterThrowing(pointcut = "aopWebLog()",throwing = "ex")
    public void doAfterThrowing(Exception ex){
        log.error("ERROR : {}",ex.getMessage());
    }
}
